package com.yinda.dt.produce.module.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xcgame.srv.SuperRecyclerView;
import com.yinda.dt.produce.R;
import com.yinda.dt.produce.app.DemoActivity;
import com.yinda.dt.produce.app.DemoConfig;
import com.yinda.dt.produce.app.MyResponseCallback;
import com.yinda.dt.produce.module.login.LoginActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;

public class SearchActivity extends DemoActivity implements View.OnClickListener, TextWatcher {

    private int status;
    private String approvalCode;

    private ArrayList<JSONObject> orders;

    private LinearLayout ll_left;

    private SuperRecyclerView srv_content;
    private OrderListAdapter adapter;

    private EditText et_keyword;

    private Call call;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        status = getIntent().getIntExtra("status", 1);
        approvalCode = getIntent().getStringExtra("approvalCode");

        et_keyword = (EditText) findViewById(R.id.et_keyword);
        et_keyword.addTextChangedListener(this);

        ll_left = (LinearLayout) findViewById(R.id.ll_left);
        ll_left.setOnClickListener(this);

        srv_content = (SuperRecyclerView) findViewById(R.id.srv_content);
        srv_content.setPullRefreshEnabled(false);
        srv_content.setLoadMoreEnabled(false);
        srv_content.setEmptyView(R.layout.view_no_date);
        orders = new ArrayList<>();
        adapter = new OrderListAdapter();
        srv_content.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_left) {
            finish();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (call != null) {
            call.cancel();
        }

        orders.clear();
        adapter.notifyDataSetChanged();

        String keyword = s.toString();
        if (!keyword.equals("")) {
            search(keyword);
        }

    }

    private void search(String keyword) {
        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!search.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("status", status);
            jsonParams.put("approvalCode", approvalCode);
            jsonParams.put("keyword", keyword);
            call = post(url, jsonParams, new MyResponseCallback() {

                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {
                        JSONObject jsonHead = jsonResult.getJSONObject("head");
                        int status = jsonHead.getInt("status");
                        String info = jsonHead.getString("info");
                        if (status == 1) {

                            JSONArray jsonOrders = jsonResult.getJSONArray("data");

                            for (int i = 0; i < jsonOrders.length(); i++) {
                                JSONObject jsonOrder = jsonOrders.getJSONObject(i);
                                orders.add(jsonOrder);
                            }

                            adapter.notifyDataSetChanged();

                        } else {
                            if (info.contains("key无效") || info.toLowerCase().contains("loginout") || info.contains("未登录")) {
                                DemoConfig.getInstance(getContext()).setKey("");
                                DemoConfig.getInstance(getContext()).setIsLogin(false);
                                showToast("请重新登录");
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } else {
                                showToast(info);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ViewHolder> {

        class ViewHolder extends RecyclerView.ViewHolder {

            LinearLayout ll_item;
            TextView tv_orderTitle;
            TextView tv_orderTime;
            TextView tv_orderUser;
            TextView tv_orderNumber;
            ImageView iv_refuse;
            TextView tv_revoke;

            public ViewHolder(View itemView) {
                super(itemView);

                ll_item = (LinearLayout) itemView.findViewById(R.id.ll_item);
                tv_orderTitle = (TextView) itemView.findViewById(R.id.tv_orderTitle);
                tv_orderTime = (TextView) itemView.findViewById(R.id.tv_orderTime);
                tv_orderUser = (TextView) itemView.findViewById(R.id.tv_orderUser);
                tv_orderNumber = (TextView) itemView.findViewById(R.id.tv_orderNumber);
                iv_refuse = (ImageView) itemView.findViewById(R.id.iv_refuse);
                tv_revoke = (TextView) itemView.findViewById(R.id.tv_revoke);
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(SearchActivity.this).inflate(R.layout.adapter_order_list, parent, false);
            return new ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            try {
                final JSONObject jsonOrder = orders.get(position);
                String title;
                switch (jsonOrder.getString("approvalCode")) {
                    case "1":
                        title = "订单申请";
                        break;
                    case "2":
                        title = "订单审批";
                        break;
                    case "3":
                        title = "计划安排";
                        break;
                    case "4":
                        title = "技术资料";
                        break;
                    case "5":
                        title = "半成品";
                        break;
                    case "6":
                        title = "黑件出厂";
                        break;
                    case "7":
                        title = "镀锌申请";
                        break;
                    case "8":
                        title = "镀锌申请-副总审批";
                        break;
                    case "9":
                        title = "白件质检";
                        break;
                    case "10":
                        title = "计划发货";
                        break;
                    case "11":
                        title = "项目收货";
                        break;
                    case "12":
                        title = "新建项目施工";
                        break;
                    case "13":
                        title = "施工质检";
                        break;
                    case "14":
                        title = "计划安排副总审核";
                        break;
                    case "15":
                        title = "改造项目施工";
                        break;
                    case "16":
                        title = "零星项目施工";
                        break;
                    case "18":
                        title = "外协审批";
                        break;
                    default:
                        title = "未知";
                        break;
                }
                holder.tv_orderTitle.setText(title);
                holder.tv_orderUser.setText(jsonOrder.getJSONObject("user").getString("userName"));
                holder.tv_orderTime.setText(jsonOrder.getString("orderTime"));
                holder.tv_orderNumber.setText(jsonOrder.getString("orderId"));

                if (jsonOrder.getString("reviewStatus").equals("0")) {
                    holder.iv_refuse.setVisibility(View.INVISIBLE);
                } else {
                    holder.iv_refuse.setVisibility(View.VISIBLE);
                }

                holder.ll_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            Intent intent = new Intent(SearchActivity.this, OrderDetailActivity.class);
                            intent.putExtra("orderId", jsonOrder.getString("Id"));
                            intent.putExtra("approvalCode", jsonOrder.getString("approvalCode"));
                            intent.putExtra("orderType", jsonOrder.getString("orderType"));
                            intent.putExtra("orderStatus", jsonOrder.getString("orderstatus"));
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            if (orders == null) {
                return 0;
            }
            return orders.size();
        }
    }

}
